<template>
  <div id="bulkOrder">
    <div class="filter-box">
      <div class="top-box">
          <div class="box-title">收货信息</div>
          <a-button type="primary" @click="book">立即预订</a-button>
      </div>
      <a-row class="info">
        <a-col :span="8">
            <span class="stars">*</span>
            <span class="info-left">购入项目</span>
            <a-select
                v-model="form.ncProjectId"
                style="width: 250px;"
                @change="selectCompany"
                @search="searchProject"
                @popupScroll="popupScroll2"

                :filterOption="filterOption"
                :showSearch="true"
                allowClear
                placeholder="请选择购入项目">
                <a-select-option
                  v-for="(item,index) in projects"
                  :key="index"
                  :value="item.value"
                  >
                  {{ item.label }}
                </a-select-option>
          </a-select>
        </a-col>
        <a-col :span="8">
            <span class="stars">*</span>
            <span class="info-left">购入仓库</span>
            <a-select
              v-model="form.warehouseId"
              style="width: 250px;"
              :filterOption="filterOption"
              :showSearch="true"
              allowClear
              @popupScroll="popupScroll"
              @search="val => searchWarehouseId(val)"
              @select="selectWarehouseId"
              placeholder="请选择购入仓库">
                <a-select-option
                  v-for="(item,index) in warehouses"
                  :key="index"
                  :value="item.value"
                  >
                  {{ item.label }}
                </a-select-option>
          </a-select>
        </a-col>
        <a-col :span="8">
            <span class="stars">*</span>
            <span class="info-left">购入组织</span>
            <a-select v-model="form.orgName" style="width: 250px;" disabled  allowClear placeholder="请选择购入组织">
                <!-- <a-select-option
                  v-for="(item,index) in typeOne"
                  :key="index"
                  :value="item.value"
                  >
                  {{ item.label }}
                </a-select-option> -->
          </a-select>
        </a-col>
      </a-row>
      <a-row class="info">
        <a-col :span="8">

            <span class="info-left" style="padding-left: 15px;"><span class="stars">*</span>联系人</span>
            <a-input
              v-model="form.recMan"
              placeholder="请输入联系人"
              style="width: 250px;"
            />
        </a-col>
        <a-col :span="8">
            <span class="stars">*</span>
            <span class="info-left">联系电话</span>
            <a-input-number
              v-model="form.recPhone"

              placeholder="请输入联系电话"
              style="width: 250px;"
            />
        </a-col>
        <a-col :span="8">
            <span class="stars">*</span>
            <span class="info-left">订单编号</span>
            <a-input
              v-model="form.shopOrderSn"
              placeholder="请输入订单编号"
              style="width: 250px;"
              disabled
            />
        </a-col>
      </a-row>
      <a-row class="info">
          <a-col :span="15" class="address">
            <span class="stars">*</span>
                <span class="info-left">收货地址</span>
                <a-textarea
                    v-model="form.recAddress"
                    placeholder="请填写收货地址"
                    :auto-size="{ minRows: 3, maxRows: 5 }"
                />
          </a-col>
      </a-row>
    </div>
    <div class="container">
      <div class="container-title">预订明细</div>
      <div class="title-info">
        <span class="info-left">项目：</span><span class="info-right">{{ncProjectName}}</span>
        <span class="info-left">所属组织：</span><span>{{orgName}}</span>
      </div>
      <div class="order-table">
        <a-row class="table-header">
          <a-col :span="1" ><a-checkbox v-model="checkAll" @change="changeCheckAll">
              </a-checkbox></a-col>
          <a-col :span="8" class="header-item">商品</a-col>
          <a-col :span="3" class="header-item">单价</a-col>
          <a-col :span="3" class="header-item">可预订数量</a-col>
          <a-col :span="4" class="header-item">预订单价</a-col>
          <a-col :span="4" class="header-item">预订数量</a-col>
        </a-row>
      </div>

      <div
          class="table-item"
          v-for="(item, index) in Data"
          :key="index"
        >
          <a-row class="table-item-body">
            <a-col :span="1">
              <a-checkbox v-model="item.check"  @change="checkItem(item)">
              </a-checkbox>
            </a-col>
            <a-col :span="8" class="flex-row">
              <img :src="item.goodsPic" class="table-pic" />
              <div class="table-info">
                <p class="info-name">{{ item.ncMaterielName }}</p>
                <p>规格：{{ item.goodsSpec }}</p>
                <p>单位：{{ item.goodsUnit }}</p>
              </div>
            </a-col>
            <a-col :span="3" class="item-col">
              ￥{{ item.unitPrice }}
            </a-col>
            <a-col :span="3" class="item-col">
              {{ item.upNumber }}
            </a-col>
            <a-col :span="4">
              <a-input-number
                v-model="item.buyPrice"
                placeholder="请输入预订单价"
              />
            </a-col>
            <a-col :span="4">
              <a-input-number
                v-model="item.num"
                placeholder="请输入预订数量"
              />
            </a-col>

          </a-row>
        </div>
        <div class="table-empty" v-if="!Data.length">
          <img src="@/assets/images/empty.png" />
          <span>暂无数据</span>
        </div>
      <!-- <div class="page-box">
        <a-pagination
          size="small"
          :total="pageConfig.total"
          show-quick-jumper
          :show-total="(total) => `总共 ${pageConfig.total} 条数据`"
          @change="changePage"
        />
      </div> -->
    </div>
    <a-modal
      v-model="showVisible"
      title=""
      cancel-text="返回集市"
      ok-text="订单详情"
      style="text-align: center;"
      @ok="handleOk"
      @cancel="handleCancel">
      <p class="model-icon"><a-icon type="check-circle" class="icon" /></p>
      <p class="model-text">下单成功</p>
      <p>请等待出售方发货</p>
    </a-modal>
  </div>
</template>

<script lang="ts">
import { Component, Vue, Watch } from 'vue-property-decorator';

@Component
export default class bulkOrder extends Vue {
  form: any = {
    orgName: undefined,
    orgCode: undefined,
    warehouseId: undefined,
    warehouseName: undefined,
    recMan: undefined,
    recPhone: undefined,
    recAddress: undefined,
    ncProjectId: undefined,
    shopOrderSn: 'YD' + new Date().getTime() + Math.floor(Math.random() * 10000)
  }
  warehouseIdVal:any = ''
  Data: any = [];
  pageConfig: any = {
    current: 1,
    total: 10,
    pageSize: 10
  }
  searchValue:any = ''
  projects: any = [] // 购入项目列表
  warehouses: any = [] // 购入仓库
  warehPage:any = 1
  checkGoodsList: any = [] // 选中的商品列表
  ncProjectName: any = '' // 项目名称
  orgName: any = '' // 组织名称
  shopOrderTitleId: any = '' // 预订成功返回的id,用于跳转到订单详情
  checkAll:boolean= false
  showVisible:boolean= false
  tt:any = null
  pkOrgP:any = ''
  projectsPage:any = 1
  get ncProjectId () {
    return this.$route.query.ncProjectId
  }
  get goodsId () {
    return this.$route.query.goodsId
  }

  init () {
    this.getList()
    this.getProjects()
    this.getPersonalInfo()
  }
  getPersonalInfo () {
    let data = {
      adminId: JSON.parse(localStorage.getItem('userInfo') || '{}').adminId
    }
    this.$api.memberDetailFetch(data).then((res:any) => {
      this.$set(this.form, 'recMan', res.data.memberName)
      this.$set(this.form, 'recPhone', res.data.memberPhone)
    })
  }
  searchProject (val:any) {
    console.log(val, '==val=')
    this.shearchVal = val
    clearTimeout(this.tt)
    this.tt = setTimeout(() => {
      this.form.searchProject = undefined
      this.projectsPage = 1
      this.projects = []
      this.getProjects()
    }, 500);
  }
  selectWare (val:any) {
    this.warehouseIdVal = ''
    clearTimeout(this.tttt)
    this.tttt = setTimeout(() => {
      this.warehPage = 1
      this.warehouses = []
      this.getWarehouses(this.form.ncProjectId, this.pkOrgP)
    }, 500);
  }
  selectWarehouseId (val:any) {
    console.log(val, '===')
  }
  searchWarehouseId (val:any) {
    this.warehouseIdVal = val
      clearTimeout(this.tttt)
      this.tttt = setTimeout(() => {
        this.warehPage = 1
        this.warehouses = []
        this.getWarehouses(this.form.ncProjectId, this.pkOrgP)
      }, 500);
  }
  getList () {
    let data = {
      page: this.pageConfig.current,
      size: this.pageConfig.pageSize,
      ncProjectId: this.ncProjectId
    };
    this.$api.goodsList2Fetch(data).then((res: any) => {
      this.ncProjectName = res.data.records[0].ncProjectName
      this.orgName = res.data.records[0].orgName
      this.Data = res.data.records[0].goods.map((item:any) => ({...item, buyPrice: item.unitPrice, num: item.upNumber}))
      if (this.goodsId) {
        this.Data = this.Data.filter((item:any) => {
          if (item.goodsId === this.goodsId) {
            return item
          }
        })
      }
      this.pageConfig.total = res.data.records[0].goods.length
      if (!this.Data.length && this.pageConfig.current > 1) {
        --this.pageConfig.current
        this.getList()
      }
    })
  }
  changePage (val: number) {
    this.pageConfig.current = val;
    this.getList();
  }
  // 立即预订
  book () {
    if (this.form.ncProjectId === undefined) return this.$message.error('请选择购入项目')
    if (this.form.warehouseId === undefined) return this.$message.error('请选择购入仓库')
    if (this.form.recMan === undefined) return this.$message.error('请输入联系人')
    if (this.form.recPhone === undefined) return this.$message.error('请输入联系电话')
    if (this.form.recAddress === undefined) return this.$message.error('请输入收货地址')
    let obj :any = {}
    obj = this.warehouses.find((item:any) => { return item.value === this.form.warehouseId })
    this.form.warehouseName = obj.label;
    if (this.checkGoodsList.length === 0) return this.$message.error('请先选择商品')
    for (let i = 0; i < this.checkGoodsList.length; i++) {
      if (this.checkGoodsList[i].buyPrice === 0 || this.checkGoodsList[i].buyPrice === null) return this.$message.error('请输入预订单价')
      if (this.checkGoodsList[i].num === 0 || this.checkGoodsList[i].num === null) return this.$message.error('请输入预订数量')
    }
    let rorderAdds:any = []
    rorderAdds = this.checkGoodsList.map((item:any) => (
      {
        goodsId: item.goodsId,
        ncProjectId: this.form.ncProjectId,
        ncWarehouseId: this.form.warehouseId,
        buyPrice: item.buyPrice,
        num: item.num,
        orgCode: this.form.orgCode,
        orgName: this.form.orgName,
        rec_address: this.form.recAddress,
        rec_man: this.form.recMan,
        rec_phone: this.form.recPhone
      }))
    let data = {
      ...this.form,
      rorderAdds
    }
    this.$api.orderAddOrder2Fetch(data).then(res => {
      this.showVisible = true
      this.shopOrderTitleId = res.data.shopOrderTitleId
    })
  }
  // 项目列表
  getProjects () {
    let data = {
      page: this.projectsPage,
      size: 100,
      searchValue: this.shearchVal
    }
    this.$api.projectRoleProjectListFetch(data).then((res: any) => {
      let projects = this.projects.concat(res.data.records.map((item: any) => ({label: item.ncProjectName, value: item.ncProjectId, pkOrg: item.pkOrg})))
      this.projects = projects
    })
  }
  popupScroll2 (e:any) {
    const { scrollHeight, scrollTop, clientHeight } = e.target
      if (Math.floor(scrollHeight - scrollTop) === clientHeight) {
        this.projectsPage++
        this.getProjects()
      }
  }
  // 选择购入单位
  selectCompany (val:any) {
      this.shearchVal = val
    // clearTimeout(this.tt)
    // this.tt = setTimeout(() => {
    //   this.form.ncProjectId = undefined
    //   this.projectsPage = 1
    //   this.projects = []
    //   this.getProjects()
    // }, 500);
    // this.warehouses = []
    this.$set(this.form, 'warehouseId', undefined)
    let list = this.projects.filter((item:any) => { return item.value === this.form.ncProjectId })
    this.form.ncProjectName = list[0].label
    let pkOrg = list[0].pkOrg
    this.pkOrgP = list[0].pkOrg
    if (this.form.ncProjectId) {
      this.getWarehouses(this.form.ncProjectId, pkOrg)
    }
  }

  // 滚动选择框时执行
  popupScroll (e:any) {
    const { scrollHeight, scrollTop, clientHeight } = e.target
      if (Math.floor(scrollHeight - scrollTop) === clientHeight) {
        this.warehPage++
        this.getWarehouses(this.form.ncProjectId, this.pkOrgP)
      }
  }

  // 仓库列表
  getWarehouses (val:any, pkOrg:any) {
    let warehouses = []
    let data = {
      ncProjectId: val,
      pkOrg,
      page: this.warehPage,
      size: 200,
      searchValue: this.warehouseIdVal
    }
    this.$api.orderWarehousePageFetch(data).then((res: any) => {
      warehouses = res.data.records.map((item: any) => ({label: item.ncWarehouseName, value: item.ncWarehouseId}))
      this.warehouses = this.warehouses.concat(warehouses)
      if (res.data.records.length > 0) {
        this.form.orgName = res.data.records[0].orgName
        this.form.orgCode = res.data.records[0].orgCode
      } else {
        this.form.orgName = ''
        this.form.orgCode = ''
      }
    })
  }
  // 过滤
  filterOption (value:any, option:any) {
    return option.componentOptions.children[0].text.indexOf(value) >= 0
  }
  // 选择每项
  checkItem (item:any) {
    let newArr :any = []
    if (item.check === true) {
      this.checkGoodsList.push(item)
    } else {
      this.checkGoodsList.forEach((element:any, index:any) => {
        if (element.goodsId !== item.goodsId) {
            newArr.push(this.checkGoodsList[index])
        }
      });
      this.checkGoodsList = newArr
    }
    console.log(this.checkGoodsList);
  }
  // 全选
  changeCheckAll () {
    let newArr :any = []
    for (let i = 0; i < this.Data.length; i++) {
      this.$set(this.Data[i], 'check', this.checkAll)
      // this.Data[i].check = this.checkAll
      if (this.Data[i].check === true) {
        this.checkGoodsList.push(this.Data[i])
      } else {
        this.checkGoodsList = newArr
      }
    }
    console.log(this.checkGoodsList);
  }
  // 弹框确认
  handleOk () {
    this.showVisible = false
    this.$router.replace({
      path: '/allot/myPurchase/detail',
      query: {
        shopOrderTitleId: this.shopOrderTitleId
        }
      })
  }
  // 弹框返回
  handleCancel () {
    this.showVisible = false
    this.$router.push('/allot/market')
  }
}
</script>

<style lang="scss" scoped>
#bulkOrder {
    .top-box{
      margin-bottom: 15px;
        .box-title{
            font-size: 16px;
            font-weight: 700;
            padding-left: 5px;
            color: #000;
            height: 15px;
            line-height: 15px;
            border-left: 3px solid rgb(62, 149, 231);
        }
    }
    .info{
        padding: 10px 0;
        .address{
          display: flex;
        }
        .stars{
          color: #E14C46;
          margin-right: 5px;
        }
        .info-left{
            width: 65px;
            margin-right: 10px;

        }
    }
    .container{
      height: 450px;
      overflow-x: hidden;
			overflow-y: scroll;
    }
    .container::-webkit-scrollbar{
			display: none;
		}
    .container-title{
      font-size: 16px;
      font-weight: 700;
      padding-left: 5px;
      color: #000;
      height: 15px;
      line-height: 15px;
      border-left: 3px solid rgb(62, 149, 231);
    }
    .title-info{
      margin: 20px 0;
      font-size: 16px;
      .info-left{
        font-weight: 700;
      }
      .info-right{
        margin-right: 80px;
      }
    }
    .header-item{
      text-align: center;
    }
    .table-item{
      .table-item-body {
        border-bottom: 1px solid #F1F1F1;
        // border-top: 1px solid #F1F1F1;
        // margin-bottom: 16px;
        .ant-col {
            height: 152px;
            padding: 16px 20px;
            border-right: 1px solid #F1F1F1;
            display: flex;
            flex-direction: column;
            justify-content: center;
            color: #333;
            &:last-child {
                border-right: none;
            }
            p {
                margin-bottom: 0;
            }
            .table-pic {
                max-width: 160px;
                width: 50%;
                height: 120px;
                display: block;
                object-fit: cover;
                margin-right: 24px;
            }
            .table-info {
                display: flex;
                flex-direction: column;
                p {
                    font-size: 13px;
                    color: #999;
                }
                .info-name {
                    // @include limitLine(2);
                    margin-bottom: 16px;
                    font-size: 14px;
                    color: #000;
                    font-weight: 700;
                    // cursor: pointer;
                    // &:hover {
                    //     text-decoration: underline;
                    // }
                }
            }
        }
        .flex-row {
            flex-direction: row;
            align-items: center;
            justify-content: flex-start;
            .ant-btn {
                margin-right: 12px;
                font-size: 12px;
            }
        }
        .item-col{
          text-align: center;
        }

    }
  }
}
.model-icon{
  color: green;

  .icon{
    font-size: 50px;
  }
}
.model-text{
  font-weight: 700;
  font-size: 16px;
}
/deep/ .ant-select-selection-selected-value, .ant-input[disabled]{
  color: rgba(0, 0, 0, 0.8);
}
/deep/ .ant-input-number-input{
   color: rgba(0, 0, 0, 0.8) ;
 }
</style>
